package io.netty.example.test.client;

import com.alibaba.fastjson.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyClient {
    static ChannelFuture future = null;
    static {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        ClientHandler clientHandler = new ClientHandler();

        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
//                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(clientHandler);
//                    ch.pipeline().addLast(new LengthFieldPrepender(4, false));
                ch.pipeline().addLast(new StringEncoder());
            }
        });
        try {
            future = bootstrap.connect("localhost", 9999).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {

//        for (int i = 0; i < 100; i++) {
            sendMsg("hello");
//        }

//        try {
//
////            ChannelFuture localhost = bootstrap.connect("localhost", 9999).sync();
//
//            ChannelFuture future = pool.borrowObject();
//
//            RequestFuture requestFuture = new RequestFuture();
//            requestFuture.setId(1);
//            requestFuture.setRequest("hwllo world");
//
//            String s = JSONObject.toJSONString(requestFuture);
//            future.channel().writeAndFlush(s);
//
//            ClientHandler clientHandler = future.channel().pipeline().get(ClientHandler.class);
//
//            Response response = clientHandler.getPromise().get();
//            System.out.println(JSONObject.toJSONString(response));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    private static void sendMsg(String msg){
        RequestFuture requestFuture = new RequestFuture();
        requestFuture.setRequest(msg);
        future.channel().writeAndFlush(JSONObject.toJSONString(requestFuture));
        Object result = requestFuture.get();
        System.out.println(result);
    }
}
